<?php

namespace app\api\controller;

use alipay\aop\AopClient;
use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\campsite\Order as CampsiteOrder;
use app\common\model\events\Sign;
use app\common\model\fittings\Order as FittingsOrder;
use app\common\model\lease\Order as LeaseOrder;
use app\common\model\modify\Order as ModifyOrder;
use app\common\model\MoneyLog;
use app\common\model\order\Order as OrderOrder;
use app\common\model\recharge\Order;
use app\common\model\User;
use app\common\model\user\Info;
use app\common\model\user\Level;
use app\common\model\user\Rechargeoder;
use think\Db;
use think\Env;
use think\Log;

/**
 * 回调接口
 * 
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 支付宝回调
     */
    public function alipayNotify()
    {
        $post = $_POST;
        if (empty($post)) { //判断POST来的数组是否为空
            return false;
        }
        Log::write('记录日志：' . json_encode($post), 'err');
        $post['fund_bill_list'] = htmlspecialchars_decode($post['fund_bill_list']);
        $aop = new AopClient();
        $alipayrsaPublicKey = config('site.alipay_public_key');
        $check = $aop->rsaCheckV1($post, $alipayrsaPublicKey, "RSA2");
        Log::write('验证结果:' . json_encode($check));
        extract($post);
        if ($check) {
            //商户订单号
            //支付宝交易号
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
                $str = substr($out_trade_no, 0, 2);
                if ($str == 'NO') {
                    Pay::orderFulfillment($out_trade_no,  $trade_no);
                }
                echo "success";
            } else {
                Log::error('trade_status不存在:');
            }
        } else {
            //验证失败
            echo "fail";   //请不要修改或删除
        }
    }

    /**
     * 微信回调
     */
    public function wechatNotify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        // $data='{"id":"02a6d697-b3ab-51d5-9c60-f3544c2022b2","create_time":"2024-03-20T11:03:42+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"Aq8TVn7TX7W4jcCWdKve/2Hvorzpz1pmsm8cK8nvmS/LyxSDbt+AnlAIlFsuHmlEssyovPZqg61RyoQ+wL4DJnobpvAguRqE7JK/cKLfaPxVbw7RnybO3iKvcTZ6NTMh+qJTlbN+PnUlGbRJ97qyU1fV1XuU4LvlXrMG8CLaXQnV3iAxip2Q5K5h2UGZSUjNmo+PiAcIPqlaFKEEFO8lsvC09YkCKepKZjIXQixCHuM8tyPNQwgV5YgK4/9GzcVMT56i/DSghhhluTmuDPeCm+r4V4uiIQdNOX7HIYM0I1ISW+XVtPBhrYUWQVnfAEhCRhZnMtEf6sA0Z4Au6wojZlAwAwSaRiJCEKVd9xRnzzwPTBeusmv+LAX/GJ6NIfzAZLph2nPniCpp31TUHn42DfwLtzyw0BXcVnPBjuVVR0hVIjruUHL8ZvZUqsIJ53pYXdE6hgSIK+/Avy+gPttX8oc/HuZT5i6YnoBx4drcPak9iAULlrPGOJVpTY0xFwQwubjsAuZkjxTncNxgaSxUf3zCyuk/6ezlAe9zmFHyttClUAVXS1uS7gfCx4FeA3rNQ+We9/p8tRY=","associated_data":"transaction","nonce":"TxZtHSYPQTsv"}}';
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, Env::get('wechat.apiv3'));

            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'recharge':
                            Pay::rechargeFulfillment($order_sn, $transaction_id);
                            break;
                        case 'order':
                            $order = OrderOrder::get(['sn' => $order_sn]);
                            Pay::orderFulfillment($order, $transaction_id);
                            break;
                    }

                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return 'SUCCESS';
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return 'error';
                }
            }
        }
    }

    //退款回调地址
    public static function refundNotify()
    {
        $notifiedData = file_get_contents('php://input');
        $data = json_decode($notifiedData, true);
        Log::write('验证退款：' . $data);

        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, Env::get('wechat.apiv3'));
            $orderData = json_decode($orderData, true);
            Log::write('退款成功：' . $orderData);

            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order = Sign::get(['transaction_id' => $transaction_id]);
                if ($order->pay_status == '-1') {
                    return json(['code' => 'SUCCESS', 'message' => '成功']);
                }
                $order->pay_status = '-1';
                $order->canceltime = time();
                $order->cancel_fee = $orderData['amount']['refund'];
                $order->save();
                /*业务处理*/
                return json(['code' => 'SUCCESS', 'message' => '成功']);
            }
        }
    }
}
